package com.contest.util;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

public class FileUtil {

    public static String uploadFile(HttpServletRequest request, CommonsMultipartFile avatar) {
        String fileName = avatar.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf("."));
        String filePath = request.getSession().getServletContext().getRealPath(File.separator);
        String saveName = File.separator + "image" + File.separator + UUID.randomUUID() + ext;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filePath + saveName);
            IOUtils.write(avatar.getBytes(), fos);
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            if (fos != null) try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String baseUrl = request.getRequestURL().toString();
        //baseUrl = baseUrl.substring(0, baseUrl.substring(0, baseUrl.lastIndexOf("/") - 1).lastIndexOf("/"));
        return saveName;
    }
}
